package com.wwg.config.ds;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @Author: wwg
 */
@Configuration
public class SlaveDataSourceConfig {

    private final static Logger logger = LoggerFactory.getLogger(SlaveDataSourceConfig.class);

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.druid.slave")
    public DataSource slaveDataSource(){
        logger.info("slave数据源初始化。。。");
        return DruidDataSourceBuilder.create().build();
    }

    @Bean
    public SqlSessionFactory slaveSqlSessionFactory(@Qualifier("slaveDataSource")DataSource slaveDataSource,
                                                    @Autowired SqlStatementInterceptor sqlStatementInterceptor) throws Exception{
        SqlSessionFactoryBean fb = new SqlSessionFactoryBean();
        fb.setDataSource(slaveDataSource);
        fb.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources("classpath:/mybatis/slave/*.xml")
        );
        fb.setPlugins(sqlStatementInterceptor);
        return fb.getObject();
    }

    @Bean(name="slaveMapperScannerConfigurer")
    public MapperScannerConfigurer slaveMapperScannerConfigurer(){
        MapperScannerConfigurer configurer = new MapperScannerConfigurer();
        configurer.setSqlSessionFactoryBeanName("slaveSqlSessionFactory");
        configurer.setBasePackage("com.wwg.mapper.slave");
        return configurer;
    }

    @Bean(name="slaveTransactionManager")
    public DataSourceTransactionManager slaveTransactionManager(@Qualifier("slaveDataSource")DataSource slaveDataSource) throws Exception{
        return new DataSourceTransactionManager(slaveDataSource);
    }


}

